package org.study.bookmanager.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.study.bookmanager.io.reponse.RestBean;
import org.study.bookmanager.io.request.User.LoginReq;
import org.study.bookmanager.io.request.User.RegisterReq;
import org.study.bookmanager.service.UserService;

@RestController
@RequestMapping(value = "/v1/user",produces = "application/json;charset=UTF-8")
@Slf4j
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/login")
    public void login(@RequestBody LoginReq req, HttpServletRequest request, HttpServletResponse response) throws Exception {
        userService.login(req,request,response);
    }

    @PostMapping("/register")
    public String register(@RequestBody RegisterReq req){
        if(req.getUsername()==null){
            return RestBean.handlerError(RestBean.Code.用户名为空);
        }
        if(req.getPassword()==null){
            return RestBean.handlerError(RestBean.Code.密码为空);
        }
        if(req.getPassword().length()<6){
            return RestBean.handlerError(RestBean.Code.密码长度小于六个字符);
        }
        Object resp=userService.register(req);
        if(RestBean.handlerError(resp)!=null){
            return RestBean.handlerError(resp);
        }
        return RestBean.success(resp);
    }

    @GetMapping("/{userName}")
    public String getUserInfo(@PathVariable String userName) {
        Object resp=userService.getUserInfo(userName);
        if(RestBean.handlerError(resp)!=null){
            return RestBean.handlerError(resp);
        }
        return RestBean.success(resp);
    }
}
